new Vue({
    el: '#app',
    data() {
        return {
            form: {
                value: '',
                PageNumber: 1,
                RowAmount: 20,
            },
            list: [],
            total: 0,
            dialogContractVisible: false,
            currentContractRow: null,
            // 顶部统一报价原信息
            pageAcquisition: null,
            currentAcqId: '',
            // 页面级分阶段付款方案（与 review_detail.html 一致展示）
            stagedPayments: [],
            // 权限相关：当前企业与来源
            enterpriseId: '',
            fromQuoteDetail: false,
        }
    },
    mounted() {
        this.getList();
    },
        methods: {
        handleBack() {
            window.location.href = './index.html';
        },
        handleSerach() {
            this.form.PageNumber = 1;
            this.getList();
        },
        formatStatus(status) {
            switch (String(status)) {
                case '0': return '待审核';
                case '2': return '通过';
                case '3': return '拒绝';
                default: return '未知';
            }
        },
        statusTagType(status) {
            switch (String(status)) {
                case '0': return 'warning';
                case '2': return 'success';
                case '3': return 'danger';
                default: return 'info';
            }
        },
        handlePageChange(page) {
            this.form.PageNumber = page;
            this.getList();
        },
        getList() {
            const enterpriseId = $.cookie('enterprise') || '';
            const keyword = this.form.value || '';
            const acqId = (function () {
                try { return getQueryObject(window.location.href, 'acqId') || ''; } catch (e) { return ''; }
            })();
            // 记录当前报价编号
            this.currentAcqId = acqId;
            // 记录当前企业与来源标记（从“我的报价”进入时隐藏操作按钮）
            this.enterpriseId = enterpriseId;
            this.fromQuoteDetail = !!acqId;

            let condition = `Row_Status IN ('0','2','3')`;
            // 指定报价编号筛选或按当前登录企业筛选
            if (acqId) {
                condition += ` AND Acquisition_Unit_Price_SerialNumber='${acqId}'`;
            } else if (enterpriseId) {
                condition += ` AND Enterprise_Info_SerialNumber='${enterpriseId}'`;
            }
            if (keyword) {
                const kw = String(keyword).replace(/'/g, "''");
                condition += ` AND (Acquisition_Order_SerialNumber LIKE '%${kw}%' OR Enterprise_Info_SerialNumber LIKE '%${kw}%')`;
            }

            httpRequest({
                url: '/generalBusiness/generalQueryByTableName',
                data: {
                    Data: 'acquisition_order',
                    Condition: condition,
                    PageNumber: this.form.PageNumber,
                    RowAmount: this.form.RowAmount,
                },
                type: 'GET'
            }).then(async res => {
                if (Array.isArray(res)) {
                    this.list = res;
                    this.total = res.length;
                } else {
                    this.list = res.Data || [];
                    this.total = Number(res.Total || 0);
                }

                // 尝试查询拒绝日志，若无该表或查询失败则忽略
                const ids = (this.list || []).map(i => i.Acquisition_Order_SerialNumber).filter(Boolean);
                if (ids.length > 0) {
                    try {
                        const logs = await httpRequest({
                            url: '/generalBusiness/generalQueryByTableName',
                            data: {
                                Data: 'acquisition_order_examine_log',
                                Condition: `Acquisition_Order_SerialNumber IN (${ids.map(id => `'${id}'`).join(',')})`
                            },
                            type: 'GET'
                        });
                        const arr = Array.isArray(logs) ? logs : (logs.Data || []);
                        const map = {};
                        arr.forEach(l => {
                            const k = l.Acquisition_Order_SerialNumber;
                            if (!map[k]) map[k] = [];
                            map[k].push(l);
                        });
                        this.list = this.list.map(row => ({
                            ...row,
                            examineLogs: map[row.Acquisition_Order_SerialNumber] || []
                        }));
                    } catch (e) {
                        // 无日志表或查询失败，忽略
                    }
                }

                // 批量查询报价原信息（acquisition_unitprice），挂载页面顶部并绑定到每条订单
                const unitIds = [...new Set((this.list || []).map(i => i.Acquisition_Unit_Price_SerialNumber).filter(Boolean))];
                if (unitIds.length > 0) {
                    try {
                        const upRes = await httpRequest({
                            url: '/generalBusiness/generalQueryByTableName',
                            data: {
                                Data: 'acquisition_unitprice',
                                Condition: `Acquisition_Unit_Price_SerialNumber IN (${unitIds.map(id => `'${id}'`).join(',')})`
                            },
                            type: 'GET'
                        });
                        const upArr = Array.isArray(upRes) ? upRes : (upRes.Data || []);
                        const upMap = {};
                        upArr.forEach(s => { upMap[s.Acquisition_Unit_Price_SerialNumber] = s; });
                        // 绑定到每条记录，便于权限判断
                        this.list = (this.list || []).map(row => ({
                            ...row,
                            originAcquisition: upMap[row.Acquisition_Unit_Price_SerialNumber] || null
                        }));
                        const firstId = (this.list[0] && this.list[0].Acquisition_Unit_Price_SerialNumber) || '';
                        this.pageAcquisition = upMap[this.currentAcqId] || upMap[firstId] || null;

                        // 页面级分阶段付款方案：按当前顶部报价编号查询并排序
                        try {
                            const idsForStage = Object.keys(upMap);
                            const stagedResAcq = idsForStage.length ? await httpRequest({
                                url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                                data: {
                                    Data: 'acquisition_unitprice_staged_payment',
                                    Condition: `Acquisition_Unit_Price_SerialNumber IN (${idsForStage.map(id => `'${id}'`).join(',')})`
                                },
                                type: 'GET'
                            }).catch(() => []) : [];
                            const stagedArrAcq = Array.isArray(stagedResAcq) ? stagedResAcq : (stagedResAcq.Data || []);
                            const orderMap = { '定金': 1, '发货': 2, '到货': 3, '尾款': 4 };
                            const currentId = (this.pageAcquisition && this.pageAcquisition.Acquisition_Unit_Price_SerialNumber) || '';
                            this.stagedPayments = (stagedArrAcq || [])
                                .filter(sp => sp.Acquisition_Unit_Price_SerialNumber === currentId)
                                .slice()
                                .sort((a, b) => (orderMap[String(a.Stage_Name || '').trim()] || 99) - (orderMap[String(b.Stage_Name || '').trim()] || 99));
                        } catch (e) {
                            this.stagedPayments = [];
                        }
                    } catch (e) {
                        // 查询失败忽略
                    }
                } else if (this.currentAcqId) {
                    // 列表为空但带有 acqId：直接查询报价原信息与阶段付款方案，用于顶部展示
                    try {
                        const upRes = await httpRequest({
                            url: '/generalBusiness/generalQueryByTableName',
                            data: { Data: 'acquisition_unitprice', Condition: `Acquisition_Unit_Price_SerialNumber='${this.currentAcqId}'` },
                            type: 'GET'
                        });
                        const upArr = Array.isArray(upRes) ? upRes : (upRes.Data || []);
                        this.pageAcquisition = (upArr && upArr[0]) ? upArr[0] : null;

                        // 顶部阶段付款方案
                        try {
                            const stagedResAcq = await httpRequest({
                                url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                                data: {
                                    Data: 'acquisition_unitprice_staged_payment',
                                    Condition: `Acquisition_Unit_Price_SerialNumber='${this.currentAcqId}'`
                                },
                                type: 'GET'
                            });
                            const stagedArrAcq = Array.isArray(stagedResAcq) ? stagedResAcq : (stagedResAcq.Data || []);
                            const orderMap = { '定金': 1, '发货': 2, '到货': 3, '尾款': 4 };
                            this.stagedPayments = (stagedArrAcq || [])
                                .slice()
                                .sort((a, b) => (orderMap[String(a.Stage_Name || '').trim()] || 99) - (orderMap[String(b.Stage_Name || '').trim()] || 99));
                        } catch (e) {
                            this.stagedPayments = [];
                        }
                    } catch (e) {
                        this.pageAcquisition = null;
                        this.stagedPayments = [];
                    }
                }
            }).catch(() => {
                this.$message.error('查询失败，请稍后再试');
            });
        },
        canOperate() { return false; },
        // 通过：将订单状态置为 2（已通过），并按报价阶段初始化 paystages
        acceptOrder(row) {
            try {
                const tableName = 'acquisition_order';
                const primaryKey = 'Acquisition_Order_SerialNumber';
                const id = row && row[primaryKey];
                if (!id) { this.$message.error('未获取到订单编号'); return; }
                if (!this.fromQuoteDetail) { this.$message.error('仅从采购订单入口可操作'); return; }

                httpRequest({
                    url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                    data: { Data: tableName, Condition: `${primaryKey}='${id}'` }
                }).then(async data => {
                    if (!Array.isArray(data) || data.length !== 1) { this.$message.error('订单不存在或存在重复记录'); return; }
                    data[0].Row_Status = '2';

                    const orderAmount = Number((data[0] && data[0].Amount) || row.Amount || 0);
                    const unitPriceId = row.Acquisition_Unit_Price_SerialNumber || data[0].Acquisition_Unit_Price_SerialNumber || '';

                    // 若尚未存在阶段付款明细，则按报价阶段生成到 acquisition_order_paystages
                    let paystagesToAdd = [];
                    try {
                        const existed = await httpRequest({
                            url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                            data: { Data: 'acquisition_order_paystages', Condition: `Acquisition_Order_SerialNumber='${id}'` },
                            type: 'GET'
                        });
                        const hasExisting = Array.isArray(existed) ? existed.length > 0 : ((existed && existed.Data) ? existed.Data.length > 0 : false);
                        if (!hasExisting && unitPriceId) {
                            const stagedRes = await httpRequest({
                                url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                                data: { Data: 'acquisition_unitprice_staged_payment', Condition: `Acquisition_Unit_Price_SerialNumber='${unitPriceId}'` },
                                type: 'GET'
                            });
                            const stagedArr = Array.isArray(stagedRes) ? stagedRes : (stagedRes && stagedRes.Data) || [];
                            paystagesToAdd = (stagedArr || []).map(sp => {
                                const percentVal = Number(sp.Percent || 0);
                                const due = Number.isFinite(orderAmount * percentVal / 100)
                                    ? Number((orderAmount * percentVal / 100).toFixed(2))
                                    : '';
                                return {
                                    Acquisition_Order_Paystages_SerialNumber: '',
                                    Acquisition_Order_SerialNumber: id,
                                    Stage_Name: sp.Stage_Name || '',
                                    Percent: sp.Percent !== undefined ? sp.Percent : '',
                                    Due_Amount: due !== '' ? String(due) : '',
                                    Trading_Amount: due !== '' ? String(due) : '',
                                    Paid_Amount: '0',
                                    Collection_Date: '',
                                    Row_Status: '0'
                                };
                            });
                        }
                    } catch (e) { /* 初始化失败不阻塞接受逻辑 */ }

                    const lJSONObject_Modify = {}; lJSONObject_Modify[tableName] = data;
                    const lJSONObject_DataSet = { Modify: lJSONObject_Modify, Add: {} };
                    if (paystagesToAdd.length > 0) lJSONObject_DataSet.Add['acquisition_order_paystages'] = paystagesToAdd;
                    const Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                    lJSONObject_DataSet['Add']['base_operation_log'] = [{
                        Operation_Type: '0', Operation_Path: getRelativePath(), Operation_Description: '接受采购订单',
                        Operation_Main, Operation_Interface: 'generalSaveByRequestBody', Operation_IP: getIpAddress()
                    }];
                    return httpRequest({ contentType: 'JSON', url: '/generalBusiness/generalSaveByRequestBody', data: JSON.stringify({ Data: lJSONObject_DataSet }) });
                }).then(res => {
                    if (res && (res.Status === 'success')) {
                        this.$message.success('已通过');
                        this.$set(row, 'Row_Status', '2');
                        // 操作完成后返回采购订单页
                        this.handleBack();
                    }
                    else if (res) { this.$message.error(res.Message || '保存失败'); }
                }).catch(() => this.$message.error('系统错误，请联系开发者!'));
            } catch (e) { console.error(e); this.$message.error('系统错误，请联系开发者!'); }
        },
        // 拒绝：将当前行状态置为3，并记录拒绝原因
        rejectOrder(row) {
            this.$prompt('请输入拒绝原因', '拒绝订单', { confirmButtonText: '确定', cancelButtonText: '取消', inputPattern: /.+/, inputErrorMessage: '拒绝原因不能为空' })
                .then(({ value }) => {
                    const reason = value || '';
                    try {
                        const tableName = 'acquisition_order';
                        const primaryKey = 'Acquisition_Order_SerialNumber';
                        const id = row && row[primaryKey];
                        if (!id) { this.$message.error('未获取到订单编号'); return; }
                        if (!this.fromQuoteDetail) { this.$message.error('仅从采购订单入口可操作'); return; }

                        httpRequest({ url: '/generalBusiness/generalQueryByTableNameWithOriginal', data: { Data: tableName, Condition: `${primaryKey}='${id}'` } })
                            .then(data => {
                                if (!Array.isArray(data) || data.length !== 1) { this.$message.error('订单不存在或存在重复记录'); return; }
                                data[0].Row_Status = '3';
                                const lJSONObject_Modify = {}; lJSONObject_Modify[tableName] = data;
                                const lJSONObject_DataSet = {
                                    Modify: lJSONObject_Modify,
                                    Add: {
                                        acquisition_order_examine_log: [{
                                            Acquisition_Order_SerialNumber: id,
                                            Reason: reason,
                                            Operation_ID: getCookie('user') || ''
                                        }],
                                        base_operation_log: [{
                                            Operation_Type: '0', Operation_Path: getRelativePath(), Operation_Description: '拒绝采购订单',
                                            Operation_Main: JSON.stringify(deepClone(lJSONObject_Modify)),
                                            Operation_Interface: 'generalSaveByRequestBody', Operation_IP: getIpAddress()
                                        }]
                                    }
                                };
                                return httpRequest({ contentType: 'JSON', url: '/generalBusiness/generalSaveByRequestBody', data: JSON.stringify({ Data: lJSONObject_DataSet }) });
                            }).then(res => {
                                if (res && (res.Status === 'success')) {
                                    this.$message.success('已拒绝');
                                    this.$set(row, 'Row_Status', '3');
                                    // 操作完成后返回采购订单页
                                    this.handleBack();
                                }
                                else if (res) { this.$message.error(res.Message || '保存失败'); }
                            }).catch(() => this.$message.error('系统错误，请联系开发者!'));
                    } catch (e) { console.error(e); this.$message.error('系统错误，请联系开发者!'); }
                }).catch(() => {});
        },
        formatRejectLog(log, idx) {
            const reason = (log && log.Reason) ? log.Reason : '';
            const time = (log && (log.Create_Date || log.Operation_Datetime)) ? `（${log.Create_Date || log.Operation_Datetime}）` : '';
            return `${idx + 1}. ${reason}${time}`;
        },
        // 格式化地址（省市区+详细地址）
        formatAddress(s) {
            if (!s) return '';
            const p = s.ProvinceNumber || '';
            const c = s.CityNumber || '';
            const d = s.CountyNumber || '';
            const a = s.Detailed_Address || '';
            return `${p}${c}${d}${a}`;
        },
        // 剩余量（兼容无该字段的情况）
        getRemainQuantity(s) {
            if (!s) return '';
            if (s.Remain_Quantity !== undefined && s.Remain_Quantity !== null) return s.Remain_Quantity;
            const t = Number(s.Total_Quantity || 0);
            const sold = Number(s.Sales_Quantity || 0);
            return t - sold;
        },
        openContractDialog(row) {
            this.currentContractRow = row || null;
            this.dialogContractVisible = true;
        },
        startOnlineSigning() {
            this.dialogContractVisible = false;
            const row = this.currentContractRow;
            if (!row) return;
            this.$message.success('已选择：线上签约');
        },
        startOfflineSigning() {
            this.dialogContractVisible = false;
            const row = this.currentContractRow;
            if (!row) return;
            this.$message.success('已选择：线下签约');
        },

    }
});